package com.fly.core.log;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.util.ResourceUtils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.fly.core.utils.SpringContextUtils;

/**
 * 
 * 可刷新日志数据库数据源
 * 
 * @author 00fly
 * @version [版本号, 2023年3月27日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public final class RefreshLogPoolManager
{
    private static DataSource dataSource;
    
    private static void init()
    {
        try
        {
            Resource resource = new ClassPathResource("jdbc-log.properties");
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        }
        catch (Exception e)
        {
            System.err.println(e.getMessage());
        }
    }
    
    /**
     * getConnection
     * 
     * @return
     * @throws SQLException
     * @throws IOException
     * @see [类、类#方法、类#成员]
     */
    public static Connection getConnection()
        throws SQLException, IOException
    {
        // 规避启用devtools插件，获取Connection失败
        if (ResourceUtils.isFileURL(ResourceUtils.getURL(ResourceUtils.CLASSPATH_URL_PREFIX)))
        {
            if (dataSource == null)
            {
                init();
            }
            return dataSource.getConnection();
        }
        
        // 启用devtools插件，下面的代码失效
        dataSource = SpringContextUtils.getBean(DataSource.class);
        // System.out.println(dataSource);
        return dataSource.getConnection();
    }
}
